package com.zxy.controlcenter.config;

import com.zxy.controlcenter.core.shiro.ShiroDbRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * shiro配置信息
 *
 * @author zxy
 * @date 2019.09.17
 */
@Configuration
public class ShiroConfig {

    /**
     * 注入自定义Realm实例
     *
     * @return Realm实例
     */
    @Bean
    public ShiroDbRealm getShiroDbRealm() {
        return new ShiroDbRealm();
    }

    /**
     * 配置SecurityManager，注入Realm实例
     *
     * @return 返回SecurityManager
     */
    @Bean
    public SecurityManager getSecurityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(getShiroDbRealm());
        return manager;
    }

    /**
     * 配置路径拦截规则
     *
     * @return 拦截规则
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 指定 SecurityManager
        bean.setSecurityManager(getSecurityManager());
        // 指定登录页面
        bean.setLoginUrl("/login");
        // 指定登录成功页面
        bean.setSuccessUrl("/index");
        // 指定没有权限跳转的url
        bean.setUnauthorizedUrl("/unauthorizedUrl");
        // 配置路径拦截规则，要有序，优先级依次降低
        Map<String, String> map = new LinkedHashMap<>();
        // anon(不需要认证) authc(需要认证)
        map.put("/doLogin", "anon");
        map.put("/**", "authc");
        bean.setFilterChainDefinitionMap(map);
        return bean;
    }
}
